﻿
#ifndef WIN_TCP_CLIENT_EVENT_LOOP_H
#define WIN_TCP_CLIENT_EVENT_LOOP_H

#include <memory>
#include <functional>
#include "Poco/Net/SocketReactor.h"
#include "zs_timer.h"
#include "tcp_conn.h"

namespace zs
{
    /* 定时器回调函数:
     * using TimerCallback = std::function<std::string()>;*/
    /*
     * socket 写事件处理器
     * using SkWriteEventHandler = std::function<void()>;
     * socket 读事件处理器
     * using SkReadEventHandler = std::function<void(std::string& msg)>;
     * socket 错误事件处理器
     * using SkErrorEventHandler = std::function<void()>;
     */
    class CZSTimer;
    class CEventLoop
    {
    public:
        CEventLoop();
        ~CEventLoop();

        void run();
        void stop();
        /*
         * brief: register timer event
         * param: long interval: 定时器的时间间隔,单位毫秒
         * param: TimerCallback timer_cb: 定时器回调函数,也就是定时器到期时执行的函数
         */
        void register_timer_event(long interval, zs::TimerCallback timer_cb);
        /*
         * brief: 添加socket写事件处理器
         */
        void add_write_event_handler(const Poco::Net::Socket& socket, zs::SkWriteEventHandler write_event_handler);
        /*
         * brief: 添加socket读事件处理器
         */
        void add_read_event_handler(const Poco::Net::Socket& socket, zs::SkReadEventHandler read_event_handler);
        void remove_event_read_handler(const Poco::Net::Socket& socket);
        void remove_event_write_handler(const Poco::Net::Socket& socket);
    private:
        void event_writable(const Poco::AutoPtr<Poco::Net::WritableNotification>& pNf);
        void event_readable(const Poco::AutoPtr<Poco::Net::ReadableNotification>& pNf);
    private:
        std::unique_ptr<Poco::Net::SocketReactor> reactor_;
        std::vector<std::unique_ptr<zs::CZSTimer>> timers_;
        zs::SkWriteEventHandler write_event_handler_;
        zs::SkReadEventHandler read_event_handler_;
    };
}




#endif //WIN_TCP_CLIENT_EVENT_LOOP_H
